<?php
/**
 * @since v1.0
 * @modify 2015.6.21
 * @copyright 深圳亿游
 */
require_once(LIB_PATH.'controller/root.con.php');

class courseCon extends rootCon{
    //预约
    public function appAction(){
        $uid = mylogin::getUid(true);
        $app = new CourseAppointment();
        $app->load();

        $course = new Course();
        $course->find($app->courseId);
        $app->schoolId = $course->schoolId;

        Traceext::addDailyAppSchool($course->schoolId);

        $app->uid = $uid;
        $app->status = STATUS_PUBLISH;
        $app->dateAndTime = r('date')."-".r('time').":00";
        $app->ip = myip::getIp();
        $saved = $app->save();
        if($saved){
            $this->j(0,"成功",$app->hide());
        }

        $this->j(-1,"保存失败");
    }



    //机构主页-》我的活动-课程列表
    public function bySchoolAction(){
        $uid = mylogin::getUid(false);

        if(!s('schoolId')){
            $this->j(-1,"缺少必要参数",['schoolId'=>r('schoolId')]);
        }
        $schoolId = r_int('schoolId');
        $school = new School();
        $school->find($schoolId);

        $course = new Course();
        $sql = "SELECT * FROM ".$course->table()." WHERE status=".STATUS_PUBLISH." AND  schoolId=$schoolId";
        $allCourse = $course->query($sql);

        $i= 0;
        foreach($allCourse as $item){
            $allCourse[$i]['distance'] = mygeo::getDistanceAuto($item['lat'],$item['lng'],r('lat'),r('lng'));
            $allCourse[$i]['addr'] = $school->addr;
            $i++;
        }

        $this->j(0,"",$allCourse);
    }

    //老师主页和老师管理端--》我的活动-课程列表
    public function byTeacherAction(){
        $uid = mylogin::getUid(false);

        if(!s('teacherId')){
            $this->j(-1,"缺少必要参数",['teacherId'=>r('teacherId')]);
        }

        $courseTeacher = new CourseTeacher();
        $courseTeacher->status = STATUS_PUBLISH;
        $courseTeacher->teacherId = r('teacherId');
        $all = $courseTeacher->findAll();

        //找课程列表
        $courseIds = [-1];
        foreach($all  as $item){
            if($item['courseId'] && $item['courseId']>0){
                $courseIds[] = $item['courseId'];
            }
        }
        $course = new Course();
        $sql = "SELECT courseName,uploadImg,price,buyCount,courseId FROM ".$course->table()." WHERE status=".STATUS_PUBLISH." AND  courseId IN (  ".join(",",$courseIds)."  )";
        $allCourse = $course->query($sql);
        $this->j(0,"",$allCourse);
    }


    //我的活动（机构在售课程）
    public function activityAction(){
        $uid = mylogin::getUid(false);

        if(!s('sellerUid')){
            $this->j(-1,"缺少必要参数",['sellerUid'=>r('sellerUid')]);
       }

        //找当前用户ID对应的学校
        $sellerUid = r_int('sellerUid');
        if(r('isDebug')){
            $sellerUid = 1;
        }


        //找学校列表
        $schoolAdmin = new SchoolAdmin();
        $schoolAdmin->uid = $sellerUid;
        $schoolAdmin->status = STATUS_PUBLISH;
        $all = $schoolAdmin->findAll();

        //找课程列表
        $schoolIds = [-1];
        foreach($all  as $item){
            if($item['schoolId'] && $item['schoolId']>0){
                $schoolIds[] = $item['schoolId'];
            }

        }
        $course = new Course();
        $sql = "SELECT courseName,uploadImg,price,buyCount,courseId FROM ".$course->table()." WHERE status=".STATUS_PUBLISH." AND  schoolId IN (  ".join(",",$schoolIds)."  )";
        $allCourse = $course->query($sql);
        $this->j(0,"",$allCourse);
    }

    public function infoAction(){
        $uid = mylogin::getUid(true);
        $info = @json_decode(stripslashes(r('courseId')));
        if(is_array($info)){//课程对比，多个课程详情
            $list = [];
            $i = 0;
            foreach($info as $courseId){
                if($i>6) break;
                $courseId = intval($courseId);
                $one = $this->getCourseInfo($courseId,$uid);
                if($courseId && $one)   $list[] = $one;
                $i++;
            }
            $this->j(0,'课程列表',$list);
        }else{//单个课程详情
            $courseId = r_int('courseId');
            $courseInfo = $this->getCourseInfo($courseId,$uid);

            $order = new Order();
            $sql = "SELECT orderId FROM ".$order->table()." WHERE buyerUid=$uid AND buyerPay>0  LIMIT 1";
            $result = $order->query($sql);
            if($result['orderId']) {
                $courseInfo['haveOrder'] = true;
            }else{
                $courseInfo['haveOrder'] = false;
            }



            //判断这个用户是否为机构管理员
            $schoolAdmin = new SchoolAdmin();
            $schoolAdmin->schoolId = $courseInfo['schoolId'];
            $schoolAdmin->uid = $uid;
            $isAdmin = $schoolAdmin->find();
            $courseInfo['isAdmin'] = $isAdmin;

            //找到老师
            $teacher      = new Teacher();
            $teacher->uid      = $uid;
            $isTeacher = $teacher->find();
            $courseInfo['isTeacher'] = $isTeacher;

            //判断这个用户是否为机构老师
            if($isTeacher){
                $courseTeacher = new CourseTeacher();
                $courseTeacher->courseId  = $courseId;
                $courseTeacher->teacherId = $teacher->teacherId;
                $isCourseTeacher = $courseTeacher->find();
                $courseInfo['isCourseTeacher'] = $isCourseTeacher;
            }else{
                $courseInfo['isCourseTeacher'] = false;
            }


            
            $courseInfo['allTeacher'] = $courseInfo['courseTeachers'];


            if(!$isCourseTeacher && !$isAdmin) Traceext::log($uid,$courseInfo['courseName'],$courseInfo['courseName'],$courseInfo['schoolId'],0,$courseId);

            
            $this->j(0,$sql,$courseInfo);
        }
    }

    private function getNationByNationId($nationId){
        $nationObj = new Nation();
        $find = $nationObj->find($nationId);
        if(!$find) return "中国";
        return $nationObj->nation;
    }


    private function getCourseInfo($courseId,$uid){
        $obj = new Course();
        $obj->courseId = $courseId;
        $sql = "SELECT * FROM ".$obj->table()." WHERE ".$obj->key()."=".$courseId." AND (`status`=".STATUS_PUBLISH." OR uid=$uid)";
        $rect = $obj->one($sql);

        $rect['testClass'] = $rect['testClass']?true:false;
        $rect['distance'] = mygeo::getDistanceAuto(mygeo::getLat($uid),mygeo::getLng($uid),$rect['lat'],$rect['lng']);

        if(!$rect) return false;

        $rect['courseTeachers'] = $this->getCourseTeacher($obj,$uid);
        $nationId = $rect['courseTeachers'][0]['nationId'];
        $rect['nation'] = $this->getNationByNationId($nationId);
        $school = new School();
        $school->find($rect['schoolId']);
        $school->hide();
        $rect['school'] = $school->arr;
        $rect['schoolName'] = $school->schoolName;

        $obj = new CourseImage();
        $rect['courseImages'] = $obj->all(['courseId',$courseId]);

        $obj = new CoursePoint();
        $points = $obj->all(['courseId',$courseId]);
        $i =0;
        foreach($points as $item){
            $pointObj = new Point();
            $pointObj->find($item['pointId']);
            $item['img'] = $pointObj->img;

            if(!preg_match("/^http/i",$item['img'])){
                $points[$i]['img']  = FRONT_URL.$item['img'];
            }
            $i++;
        }
        $rect['coursePoint'] = $points;

        $rect['learnedCount'] = $rect['learned'];
        $rect['learned'] = $this->getLearnedList($courseId);

        //星期的分析
        $rect['weekInfo'] = $rect['week'] ? mydate::getWeekInfo($rect['week']) : '';

        return $rect;
    }

    private function getLearnedList($courseId){
        $obj = new CourseLearned();
        $sql = "SELECT * FROM ".$obj->table()." WHERE  courseId=".$courseId;
        if(IS_DEBUG && r('isDebug')){
            $sql = "SELECT * FROM ".$obj->table()." LIMIT 3";
        }

        $all = $obj->query($sql);
        $i =0;
        foreach($all as $item){
            if(!preg_match("/^http/i",$item['avatar'])){
                $all[$i]['avatar']  = FRONT_URL.$item['avatar'];
            }
            $i++;
        }
        return $all;
    }

    private function getCourseTeacher($courseObj,$uid){
        $courseId = $courseObj->courseId;
        $ctObj = new CourseTeacher();
        if(r('isAdmin')|| r('isTui')){//推广员和管理员可以查看待审核和审核不通过的老师
            $sql = "SELECT  t.*  FROM ".$ctObj->table()." st LEFT JOIN tbl_teacher t ON st.teacherId=t.teacherId  WHERE st.courseId=".$courseId." AND t.status!=88 AND st.status=3";
        }else{
            $sql = "SELECT  t.*  FROM ".$ctObj->table()." st LEFT JOIN tbl_teacher t ON st.teacherId=t.teacherId  WHERE st.courseId=".$courseId." AND t.status=3 AND st.status=3";
        }
        $allTeacher = $ctObj->query($sql);//teacherName和uploadImg
        $i = 0;
        foreach($allTeacher as $item){
            $teacherLabelObj = new TeacherLabel();
            $labels = $teacherLabelObj->all(['teacherId'=>$item['teacherId'],'status'=>STATUS_PUBLISH]);
            $allTeacher[$i]['teacherLabel'] = $labels;
            if(is_numeric($allTeacher[$i]['teacherYear'])){
                $allTeacher[$i]['teacherYear'] = $allTeacher[$i]['teacherYear']."年教龄";
            }
            $i++;
        }
        return $allTeacher;
    }
	
	/**
	 * 课程分类
	 */
    public function typeAction() {
        $uid = mylogin::getUid(false);


        $rect = myredis::getArray("courseTypeRect");
        if(!$rect) {
        	//课程主分类
            $obj = new CourseMain();
            $result = $obj->all(['status', STATUS_PUBLISH], '`sort` ASC');

            //课程子分类
            $obj = new CourseSub();
            $sub = $obj->all(['status', STATUS_PUBLISH], '`sort` ASC');
            foreach ($sub as $row) {
                for ($i = 0; $i < count($result); $i++) {
                    if ($row['courseMainId'] == $result[$i]['courseMainId']) {
                        $row['courseMain'] = $row['courseSub'];
                        $result[$i]['sub'][] = $row;
                    }
                }
            }

            $rect['courseMain'] = $result;

            //----课程基础-------
            $obj = new CourseBase();
            $result = $obj->all(['status', STATUS_PUBLISH], '`sort` ASC');
            $rect['courseBase'] = $result;

            //上课人数
            $obj = new CoursePeople();
            $result = $obj->all(['status', STATUS_PUBLISH], '`sort` ASC');
            $rect['coursePeople'] = $result;

            //课程特点
            $obj = new Point();
            $result = $obj->all(['status', STATUS_PUBLISH], '`sort` ASC');
            $rect['coursePoint'] = $result;
            $rect['from'] = 'db';
            myredis::setArray("courseTypeRect",$rect,600);
        }else{
            $rect['from'] = 'cache';
        }

        //机构老师
        $schoolTeacher = new SchoolTeacher();
        $schoolTeacher->schoolId = r_int('schoolId');
        $all = $schoolTeacher->all();
        $teacherIds = [-1];
        foreach ($all as $item) {
            if ($item['teacherId']) $teacherIds[] = $item['teacherId'];
        }
        $obj = new Teacher();
        $str = join(',',$teacherIds);
        

        if(r('isTui') || r('isAdmin')){
            $con = " status IN (0,3,4) AND teacherId IN ($str) ";
        }else{
            $con = " status=".STATUS_PUBLISH."  AND teacherId IN ($str) ";
        }

        $result = $obj->all($con,'`sort` ASC');

        $rect['courseTeacher'] = $result;
        $this->j(0, "list",$rect);
    }



    public function saveAction(){
        $uid = mylogin::getUid(true);
        $obj = new Course();
        $obj->load();

        if(r('status')==5){//下线课程
            $obj->status = 5;
        }

        if($obj->courseId){//检查修改权限
            $find = $obj->find([$obj->key(),$obj->courseId]);
            if(!$find) $this->j(-3,'error key',$obj->key());
            if($obj->uid != $uid) $this->j(-4,'error uid');
            $obj->load();
        }

        if(!trim($obj->courseName)){
            $this->j(-4,'请填写课程名');
        }

        if(!$obj->courseId  && !$obj->oldPrice){//新增
            $this->j(-5,'请填写课程原价');
        }


        //---新增课程一定要设置年龄范围----
        if(!$obj->courseId && r('minAge')==''){
            $obj->minAge = 0;
        }
        if(!$obj->courseId && r('maxAge')==''){
            $this->j(-4,'请设置适用人群的年龄');
        }


        if($obj->courseLogo){
            $imgObj = new ImageFile();
            $imgObj->find($obj->courseLogo);
            $obj->uploadImg = $imgObj->uploadImg;
        }

        //@todo 检查这个用户，是否可以在这个机构下发课程
        $school = new School();
        $school->find($obj->schoolId);
        if($school->status == STATUS_PUBLISH) {//已经通过审核的机构可以直发课程
            if(!s('status')) $obj->status = STATUS_PUBLISH;
        }else{//机构没有通过审核，则为待审核
            $obj->status = STATUS_SUBMIT;
        }

        $obj->districtId = $school->districtId;
        $obj->cityIdOk = $school->cityIdOk;
        $obj->location = $school->location;
        $obj->lat = $school->lat;
        $obj->lng = $school->lng;
        $obj->geo = $school->geo;

        
        $obj->ip = myrequest::getIP();
        if(!$obj->created) $obj->created = date('Y-m-d H:i:s');
        $obj->uid = $uid;

        

        $schoolAdmin = new SchoolAdmin();
        $schoolAdmin->schoolId = $obj->schoolId;
        $schoolAdmin->uid = $uid;
        $schoolAdmin->status = STATUS_PUBLISH;
        $isSchoolAdmin  = $schoolAdmin->find();
        if($isSchoolAdmin){//管理员可以修改状态
            $obj->status = r_int('status');
        }
        $obj->save();

        $this->saveImage($obj->courseId);
        $this->saveTeacher($obj->courseId);
        $this->savePoint($obj->courseId);
        $this->j(0,'',$obj->arr);
    }

    private function savePoint($courseId){
        if(!s('coursePoint')) return; 

        $allImg = r('coursePoint');

        $rect = [];
        //删除之前的
        $teacherImage = new CoursePoint();
        $sql = "DELETE FROM " . $teacherImage->table() . " WHERE courseId=" . $courseId;
        $teacherImage->query($sql);

        //if (!is_array($allImg)) $allImg = [$allImg];
        $i = 0;
        foreach ($allImg as $tmpObj) {
            $i++;

            if (!$tmpObj->pointId) continue;
            $tmpLabel = new Point();
            $tmpLabel->find($tmpObj->pointId);


            $teacherImage = new CoursePoint();
            $teacherImage->courseId = $courseId;
            $teacherImage->pointId = $tmpObj->pointId;
            $teacherImage->pointName = $tmpLabel->pointName;
            $teacherImage->status = STATUS_PUBLISH;//自己人不用审核
            $teacherImage->save();
            $rect[] = $teacherImage->arr;
        }
    

        return $rect;
    }


    private function saveTeacher($courseId)
    {
        if(!s('courseTeachers')) return;
        $allId = r('courseTeachers');
        //删除之前的
        $obj = new CourseTeacher();
        $sql = "DELETE FROM " . $obj->table() . " WHERE courseId=" . $courseId;
        $obj->query($sql);

        if (!is_array($allId)) $allId = [$allId];
        $i = 0;
        foreach ($allId as $tmpObj) {
            $i++;
            if (!$tmpObj) continue;
            if(!is_object($tmpObj)){
                $id = $tmpObj;
            }else{//对象
                $id =  $tmpObj->teacherId;
            }


            $obj = new CourseTeacher();
            $obj->courseId = $courseId;
            $obj->teacherId = $id;
            $obj->status = STATUS_PUBLISH;//自己人不用审核
            $obj->sort = $i;//自己人不用审核
            $obj->save();
        }
    }

    private function saveImage($courseId)
    {
        if(!s('courseImages')) return ;
        $allId = r('courseImages');

        //删除之前的
        $obj = new CourseImage();
        $sql = "DELETE FROM " . $obj->table() . " WHERE courseId=" . $courseId;
        $obj->query($sql);

        if (!is_array($allId)) $allId = [$allId];
        $i = 0;
        foreach ($allId as $imgId) {
            $i++;

            if (!$imgId) continue;

            $img = new ImageFile();
            $find = $img->find($imgId);

            $obj = new CourseImage();
            $obj->courseId = $courseId;
            $obj->imageFileId = $imgId;
            $obj->img = $img->uploadImg;
            $obj->sort = $i;
            $obj->status = STATUS_PUBLISH;//自己人不用审核
            $obj->save();
        }
    }

    //采用缓存
	
	/**
	 * 首页分类课程
	 */
    public function hotAction() {
        $uid = mylogin::getUid(false);
        
        //获取全部主分类
        $main = new CourseMain();
        $all = $main->all(['status',STATUS_PUBLISH],'sort ASC');
        $i=0;
        $orderBy = mygeo::getOrderBy();
        foreach($all as $item){
            $mainId = $item['courseMainId'];
            $course = new Course();
            //查找主类的3个课程
            $sql = "SELECT * FROM ".$course->table()." WHERE status=".STATUS_PUBLISH." AND courseMainId=".$mainId." ORDER BY $orderBy  LIMIT 3 ";
            $courseList = $course->query($sql);
            $courseList = $course->hide($courseList);
            $j = 0;
            foreach($courseList as $item){
                $courseList[$j]['distance'] = mygeo::getDistanceAuto(mygeo::getLat($uid),mygeo::getLng($uid),$courseList[$j]['lat'],$courseList[$j]['lng']);//
                $courseList[$j]['schoolName'] = $this->getSchoolName($item['schoolId']);
                $courseList[$j]['uploadImg'] = $this->getSmallImg($item['uploadImg']);
                $j++;
            }
            $all[$i]['courseList'] = $courseList;
            $i++;
        }

        $this->j(0,'',$all);
    }

    private function getSmallImg($img){
        //https://img.myclhc.com/images/03aeba9e71501863aa70c6fe9c1da145.jpg
        //https://img.myclhc.com/images/90/03aeba9e71501863aa70c6fe9c1da145.jpg
        return preg_replace("/images\//","images/90/",$img);
    }

    private function getSchoolName($schoolId){
        $school = new School();
        $school->find($schoolId);
        return $school->schoolName;
    }


    //课程搜索
    public function allAction(){
        $uid = mylogin::getUid(false);
        $obj = new Course();
        $obj->load();
        $obj->status = STATUS_PUBLISH;
        if(s('districeId')){
            $obj->districtId = r_int('districeId');
        }

        $con = $obj->getConByLoad();
        if(r('keyword')){
            $key = addslashes(trim(r('keyword')));
            //$con .= " AND (courseName LIKE '%$key%' OR summary LIKE '%$key%') ";
            $con .= " AND courseName LIKE '%$key%'  ";
        }

        $sql = "SELECT * FROM ".$obj->table()." WHERE ".$con;
        switch(r('orderBy')){
            case "remark":
                $sql .= "ORDER BY totalScore DESC";
                break;
            case "effect":
                $sql .= "ORDER BY effectScore DESC";
                break;
            case "service":
                $sql .= "ORDER BY serviceScore DESC";
                break;
            case "low":
                $sql .= "ORDER BY price ASC";
                break;
             case "high":
                $sql .= "ORDER BY price DESC";
                break;

            case "distance"://zhaopeixunapi.hkbao.com/school,all?orderBy=distance&lat=39.908491&lng=116.374328
                default:
                $sql .= " ORDER BY ".mygeo::getOrderBy();
        }

        $obj->autoHide = false;
        $all = $obj->pager($sql);

        $startLat = s('lat')?r('lat'):-1;
        $startLng = s('lng')?r('lng'):-1;

        if($startLat==-1 || $startLng==-1){
            $user = new User();
            $user->find($uid);
            $startLat = $user->lat;
            $startLng = $user->lng;
        }

        $i = 0;
        foreach($all['list'] as $item){
            $distance = mygeo::getDistanceAuto($startLat,$startLng,$item['lat'],$item['lng']);
            $all['list'][$i] = $obj->hide($item);
            $all['list'][$i]['distance'] = $distance;
            $school = new School();
            $school->find($item['schoolId']);
            $all['list'][$i]['schoolName'] = $school->schoolName;
            $all['list'][$i]['uploadImg'] = $this->getSmallImg($item['uploadImg']);
            $i++;
        }

        $all['city'] = mygeo::getCity();
        $all['district'] = mygeo::getDistrictByCity($all['city'] );

        $this->j(0, "list",$all);
    }

    //其他课程，推荐课程
    public function relatedAction(){
        $courseId = r_int('courseId');
        $courseObj = new Course();
        $courseObj->find($courseId);
        $startLat = $courseObj->lat?$courseObj->lat:-1;
        $startLng = $courseObj->lng?$courseObj->lng:-1;

        $sql = "SELECT * FROM ".$courseObj->table()." WHERE courseSub=".$courseObj->courseSub." AND courseId!=$courseId AND status=3 ORDER BY ".mygeo::getOrderBy()." LIMIT 5";
        $all = $courseObj->query($sql);
        $info = 0;
        if(IS_DEBUG) $info = $sql;
        if(is_array($all)){
            $i = 0;
            foreach($all as $item){
                $schoolId = $item['schoolId'];
                $school = new School();
                $school->find($schoolId);
                $all[$i]['addr'] = $school->addr;
                $all[$i]['schoolName'] = $school->schoolName;
                $distance = mygeo::getDistanceAuto($startLat,$startLng,$school->lat,$school->lng);
                $all[$i]['distance'] = $distance;
                $i++;
            }
        }

        $this->j(0,$info,$all);       
    }

    


    public function listAction() {
        $uid = mylogin::getUid(true);
        $obj = new Course();
        $obj->load();
        if(r('isAdmin')){
            if(s('status'))   $obj->status = r_int('status');
        }

        if(!$obj->schoolId){
            $this->j(-1,'需要机构参数');
        }
        $schoolObj = new School();
        $schoolObj->find($obj->schoolId);


        $con = $obj->getConByLoad();

        if(r('isTui') || r('isAdmin')){
            $con .=" AND uid=$uid AND status!=88 ";
        }else{
            $con .=" AND status=".STATUS_PUBLISH." ";
        }

        $all = $obj->all($con);

        
        // $len = count($all);
        // $i = 0;
        // $countStatus0 = 0;
        // $countStatus3 = 0;
        // $countStatus4 = 0;
        // $countStatus5 = 0;
        // foreach($all as $item){
        //     $all[$i]['schoolName'] = $schoolObj->schoolName;
        //     $statusName = "countStatus".$item['status'];
        //     $$statusName++;
        //     $i++;
        // }

        // $all[0]['countStatus0'] = $countStatus0;
        // $all[0]['countStatus3'] = $countStatus3;
        // $all[0]['countStatus4'] = $countStatus4;
        // $all[0]['countStatus5'] = $countStatus5;
        // $all[0]['courseCount'] = $len;

        $this->j(0,'',$all);
    }


    //想学的人列表
    public function wantListAction(){
        $uid = mylogin::getUid(true);

        //当前的老师
        $teacher = new Teacher();
        $teacher->find(['uid'=>$uid]);

        //哪些课程
        $teacherCourse = new CourseTeacher();
        $teacherCourse->teacherId = $teacher->teacherId;
        $teacherCourse->status = STATUS_PUBLISH;
        $all = $teacherCourse->all();
        $allCourse = [-1];
        foreach($all as $item){
            if($item['courseId']){
                $allCourse[] = $item['courseId'];
            }
        }
        if(r('isDebug')){
            $allCourse[] = 1;
        }

        $obj = new CourseWant();
        $ids = join(",",$allCourse);
        $sql = "SELECT w.*,c.CourseName,u.nick,u.mobile,u.avatar FROM ".$obj->table()." w LEFT JOIN tbl_course c ON w.courseId=c.courseId LEFT JOIN tbl_user u ON w.uid=u.uid WHERE w.courseId IN ($ids)";
        $all = $obj->query($sql);
        $i =0;
        foreach($all as $item){
            if(!preg_match("/^http/i",$item['avatar'])){
                $all[$i]['avatar']  = FRONT_URL.$item['avatar'];
            }
            $i++;
        }

        $this->j(0,"",$all);
    }

    //想学
    public function wantAction(){
        $uid = mylogin::getUid(true);
        $courseId = r_int('courseId');
        $course = new Course();
        $find = $course->find($courseId);
        if(!$find) $this->j(-1,"参数错误",['courseId'=>$courseId]);

        $obj = new CourseWant();
        $obj->uid = $uid;
        $obj->courseId= $courseId;
        $find = $obj->find();
        if($find){//cancel
           /* $sql = "DELETE FROM ".$obj->table()." WHERE uid=$uid AND courseId=$courseId";
            $obj->query($sql);
            $course->want = $course->want-1;
            $course->save();*/
        }else{
            $obj->save();
            $course->want = $course->want+1 ;
            $course->save();
        }
        $this->j(0,"",['want'=>$course->want]);
    }

    //学过的人列表
    public function learnedListAction(){
        $uid = mylogin::getUid(true);
        $courseId = r_int('courseId');
        $this->j(0,'',$this->getLearnedList($courseId));
    }

    //学过
    public function learnedAction(){
        $uid = mylogin::getUid(true);
        $courseId = r_int('courseId');
        $course = new Course();
        $find = $course->find($courseId);
        if(!$find) $this->j(-1,"参数错误",['courseId'=>$courseId]);

        $obj = new CourseLearned();
        $obj->uid = $uid;
        $obj->courseId= $courseId;
        $find = $obj->find();
        if($find){//cancel
           /* $sql = "DELETE FROM ".$obj->table()." WHERE uid=$uid AND courseId=$courseId";
            $obj->query($sql);
            $course->learned = $course->learned-1;
            $course->save();*/
        }

        $user = new User();
        $user->find($uid);
        if($user->avatar){
            $obj->avatar = $user->avatar;
        }else{
            $obj->avatar = "/default.png";
        }

        if($user->nick){
            $obj->nick = $user->nick;
        }else{
            $obj->nick = "匿名";
        }


        $obj->save();
        $course->learned = $course->learned+1;
        $course->save();

        $order = new Order();
        $con = "buyerUid=$uid AND courseId=$courseId AND buyerPay>0";
        $find = $order->find($con);
        if($find){
            $this->j(0,"有订单",['learned'=>$course->learned,'haveOrder'=>true]);
        }else{
            $this->j(0,"没有订单",['learned'=>$course->learned,'haveOrder'=>false]);
        }
    }


}



